﻿using cludg.Infrastructure.Core.Settings;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System.IO;
using nsadv.Statistic.Repository.NHibernate.Config;

namespace nsadv.Statistic.Repository.NHibernate
{
	public class NHibernateController
	{
		protected readonly ISettings Settings;

		//public SessionController(DbDriver dbDriver, string connectionString)
		//{
		//    Configuration = Config.ConfigProvider.GetConfig(dbDriver, connectionString, MappingExtensionRegistry);
		//    Factory = Configuration.BuildSessionFactory();
		//}

		private static DbDriver GetDbDriver(string driverName)
		{
			switch (driverName)
			{
				case "SQLCompact":
					return DbDriver.SQLCompact;
				case "SQLServer":
					return DbDriver.SQLServer;
				default:
					return DbDriver.SQLServer;
			}
		}

		public NHibernateController(ISettings settings)
		{
			Settings = settings;
			Configuration = ConfigProvider.GetConfig(
				GetDbDriver(Settings["Database_Driver"].ToString()), 
				Settings["Database_ConnectionString"].ToString());
			Factory = Configuration.BuildSessionFactory();
		}

		protected readonly Configuration Configuration;
		protected readonly ISessionFactory Factory;

		public ISession OpenSession()
		{
			return Factory.OpenSession();
		}

		public void ExportScheme(string path)
		{
			using (var tw = new StreamWriter(path))
			{
				new SchemaExport(Configuration).Execute(true, false, false, null, tw);
			}
		}

		public void UpdateDatabaseSchema()
		{
			new SchemaExport(Configuration).Execute(false, true, false);
		}
	}

	public enum DbDriver
	{
		SQLServer,
		SQLCompact
	}
}